package fr.poy.mygluco.server;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.google.appengine.api.users.UserServiceFactory; 

import fr.poy.mygluco.model.AppLogs;
import fr.poy.mygluco.model.Record;
import fr.poy.mygluco.model.AppLog.LEVEL;

public class ImportExport {
	
	private static Logger log = Logger.getLogger(ImportExport.class.getName());
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	private static SimpleDateFormat stf = new SimpleDateFormat("HH:mm");
	
	
	/**
	 * extended Accucheck import (Accucheck DTD + comment + ...)
	 * @param fileContents
	 * @param logs
	 * @return a list of records beans
	 */
	public static List<Record> xmlImport(String fileContents,final AppLogs logs ){
		final String eml = UserServiceFactory.getUserService().getCurrentUser().getEmail();
		final List<Record> ret= new ArrayList<Record>(); 
		if(fileContents == null) return ret;
		try {
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			/*ACCU CHECK XML PARSER : <BG Val='212' Dt='2009/01/15' Tm='7:30' Cmt'bl abla' Evt='A+' Flg='*' Ins1='7'/> */
			parser.parse(new ByteArrayInputStream(fileContents.getBytes()), new DefaultHandler() {
			    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			        if (qName.equals("BG")) {
			        	try {
			        		DateMidnight d = new DateMidnight(sdf.parse( attributes.getValue("Dt"))); 
			        		DateTime t = new DateTime(stf.parse( attributes.getValue("Tm")));
							ret.add( 
									new Record(eml,
											d.getDayOfWeek()
											,d.toDate()
											,t.getMinuteOfDay()//t.getHours()*60+t.getMinutes() 
											,Integer.parseInt(attributes.getValue("Val"))
											,attributes.getValue("Cmt")//ajout, ne fait pas partie de la DTD accuchek
											,attributes.getValue("Evt")
											,attributes.getValue("Flg")
											,attributes.getValue("Ins1")==null?null:Integer.parseInt(attributes.getValue("Ins1"))
											,attributes.getValue("Ins2")==null?null:Integer.parseInt(attributes.getValue("Ins2"))
											,attributes.getValue("Ins3")==null?null:Integer.parseInt(attributes.getValue("Ins3"))
									)
							);
						} catch (NumberFormatException e) {
							log.log(Level.WARNING, "ERROR ligne XML format", e);
							logs.add(LEVEL.ERROR,e.getLocalizedMessage());
						} catch (ParseException e) {
							log.log(Level.WARNING, "Parse file import", e);
							logs.add(LEVEL.ERROR,e.getLocalizedMessage());
						}  
			        } 
			    }
			});
		} catch (SAXException e) {
			log.log(Level.WARNING, "newSAXParser erreur", e);
			logs.add(LEVEL.ERROR,e.getLocalizedMessage());
		} catch (ParserConfigurationException e) {
			log.log(Level.WARNING, "newSAXParser erreur", e);
			logs.add(LEVEL.ERROR,e.getLocalizedMessage());
		} catch (IOException e) {
			log.log(Level.WARNING, "IO erreur", e);
			logs.add(LEVEL.ERROR,e.getLocalizedMessage());
		}
		return ret;
	}
	
	public static String recordToXml(Record r){
		//<BG Val='212' Dt='2009/01/15' Tm='7:30' Cmt'bl abla' Evt='A+' Flg='*' Ins1='7'/>

		r.getDate().setHours(r.getTime()/60);
		r.getDate().setMinutes(r.getTime()%60);
		
		StringBuffer sb = new StringBuffer("\n<BG ");
		if(r.getBg()!=null) sb.append("Val='").append(r.getBg()).append("' ");
		sb.append("Dt='").append(sdf.format(r.getDate())).append("' "); 
		sb.append("Tm='").append(stf.format(r.getDate())).append("' ");
		if(r.getComment()!=null) sb.append("Cmt='").append(r.getComment().replace("'", " ")).append("' ");
		if(r.getEvent()!=null) sb.append("Evt='").append(r.getEvent().replace("'", " ")).append("' ");
		if(r.getFlag()!=null) sb.append("Flg='").append(r.getFlag().replace("'", " ")).append("' ");
		if(r.getIns1()!=null) sb.append("Ins1='").append(r.getIns1()).append("' ");
		if(r.getIns2()!=null) sb.append("Ins2='").append(r.getIns2()).append("' ");
		if(r.getIns3()!=null) sb.append("Ins3='").append(r.getIns3()).append("' ");
		
		sb.append("/>"); //bg
		return sb.toString();
	}

}
